const express = require('express');
const bodyParser = require('body-parser')
const apiRouter = express.Router();
const mongoose = require('../db/dataDB');
const goodsmongoose = require('../db/goodsDB');
const path= require('path');

apiRouter.use(express.urlencoded());
apiRouter.post('/register',(req,res,next)=>{
    console.log(req.body);
    let {username,pwd} = req.body;
    mongoose.create({username:username,pwd:pwd});
    res.redirect('/logon');
});
apiRouter.post('/logon',bodyParser.json(),(req,res)=>{
    let {name,pwd} = req.body;
    // console.log(req.body);
    mongoose.find().then((data)=>{
        let use = data.find((item)=>{return item.username===name&&item.pwd==pwd});
        // console.log(use);
        if(use){
            req.session.username=name;
            res.send(true);
        }else{
            res.send(false);

        }
    })
    

});
apiRouter.post('/adddata',(req,res,next)=>{
    goodsmongoose.create(req.body);
    res.redirect('/hPage');
});
apiRouter.post('/goodsEdit',(req,res)=>{
    let {_id,goodsName,goodsDetails,price,number}=req.body;
    // console.log(req.body,"haha");
    goodsmongoose.updateOne({_id:_id },{goodsName:goodsName,goodsDetails:goodsDetails,price:price,number:number}).then((data)=>{
        // console.log(data);
        res.redirect('/hPage');
    })
   
});


module.exports = apiRouter;